<template>
  <el-card class="permission-card">

    <div class="permission-title">当前角色：{{ roleName }}</div>

    <el-button
        type="primary"
        icon="Plus"
        @click="saveEdit"
        style="margin: 12px 0 20px 0;"
    >
      保存变更
    </el-button>

    <RolePermissionItem
        v-for="item in permissionsTree"
        :key="item.id"
        :item="item"
        :checked-permissions="checkedPermissions"
        @update:checkedPermissions="val => checkedPermissions = val"
    />
  </el-card>
</template>

<script setup>

import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import {ElMessage, ElMessageBox} from 'element-plus'
import RolePermissionItem from '@/views/Ye/RolePermissionItem.vue'
import {useStore} from "vuex";
import {userStore} from "@/store/index.js";


// =================================================

// =================================================

const route = useRoute()
const roleName = route.query.roleName || '系统管理'

const roleId = route.query.id;

const store = userStore();

const permissionsTree = ref([])
// const checkedPermissions = ref([])

// ✅ 递归添加 parent 引用，供子组件逻辑使用
const addParentRef = (node, parent = null) => {
  node.parent = parent
  if (node.children && node.children.length > 0) {
    node.children.forEach(child => addParentRef(child, node))
  }
}

// ✅ 获取权限树并初始化 parent 引用
const getPermissionForest = () => {
  console.log(store.user.id)
  console.log("查看角色"+roleName+"的权限")
  axios
      .post(`/rolePermission/getPermissionTreeByRole/${roleId}`,{}, {
    headers: {
      'X-Button-Title': encodeURIComponent("查看角色"+roleName+"的权限"),  // 动态传递按钮标题
      'X-User-Id': encodeURIComponent(store.user.id),  // 动态传递用户 ID
    }
  })
      .then(resp => {
        permissionsTree.value = resp.data
        permissionsTree.value.forEach(node => addParentRef(node))

        // ✅ 在此处重新提取 checkedPermissions
        checkedPermissions.value = extractCheckedIds(permissionsTree.value)


      })
      .catch(err => {
        console.error('获取权限树失败:', err)
        ElMessage.error('获取权限树失败')
      })
}

// ✅ 保存当前勾选权限
const saveEdit = () => {
  // 显示确认框
  ElMessageBox.confirm('您确定要保存当前的权限变更吗？', '保存变更', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        // 用户点击了确认，继续保存
        console.log('当前勾选的权限ID：', checkedPermissions.value)

        axios
            .post('/rolePermission/updateRolePermissions', {
              roleId: roleId,
              permissionIds: checkedPermissions.value
            })
            .then(() => {
              ElMessage.success('权限保存成功')
            })
            .catch(err => {
              ElMessage.error('权限保存失败')
              console.error(err)
            })
      })
      .catch(() => {
        // 用户点击了取消，不做任何操作
        ElMessage.info('取消保存')
      })
}


// 1. 原始后端数据（可以通过 props、接口获取）
const permissionTree = ref([/* 后端数据 */])

// 2. 初始化已勾选权限 ID 列表
function extractCheckedIds(tree) {
  const ids = []
  const traverse = (nodes) => {
    nodes.forEach(node => {
      if (node.checked) ids.push(node.id)
      if (node.children && node.children.length > 0) {
        traverse(node.children)
      }
    })
  }
  traverse(tree)
  return ids
}

const checkedPermissions = ref(extractCheckedIds(permissionTree.value))

onMounted(() => {
  getPermissionForest()
})

// ========================================================

// ============================================================================
</script>

<style scoped>
.permission-card {
  padding: 20px;
  background: #fff;
  min-height: 400px;
}
.permission-title {
  font-weight: bold;
  font-size: 18px;
  color: #333;
  margin-bottom: 8px;
}
</style>
